// import 'dart:io';

// import 'package:flutter/cupertino.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// import 'package:flutter/services.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_page.dart';
import 'package:puppy_store/pages/home/widgets/category_grids_widget.dart';
import 'package:puppy_store/pages/home/widgets/fresh_goods_widget.dart';
import 'package:puppy_store/pages/home/widgets/home_app_bar.dart';
import 'package:puppy_store/pages/home/widgets/hot_projects_widget.dart';
import 'package:puppy_store/pages/home/widgets/hot_recommends.dart';
import 'package:puppy_store/pages/home/widgets/hot_brands_widget.dart';
// import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:puppy_store/pages/home/widgets/image_swiper_widget.dart';
// import 'package:dio/dio.dart';
// import 'package:puppy_store/service/requests.dart';
import 'package:puppy_store/service/home_api.dart';
import 'package:puppy_store/models/home_model.dart';
import 'package:puppy_store/widgets/custom_image.dart';
import 'package:puppy_store/widgets/custom_refresher.dart';
import 'package:puppy_store/widgets/price_widget.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  // AutomaticKeepAliveClientMixin 需要重写wantKeepAlive这个getter属性, 是否记录状态 true 记录状态 false 不记录状态
  @override
  @protected
  bool get wantKeepAlive => true;

  // 轮播图数据
  List<ImageBannersModel>? imageBanners;

  // 分类快捷入口数据
  List<CategoryGridsModel>? categoryGrids;

  // 热门推荐数据
  List<HotRecommendsModel>? hotRecommends;

  // 新鲜好物数据
  List<FreshGoodsModel>? freshGoods;

  // 热门品牌数据
  List<HotBrandsModel>? hotBrands;

  // 热门专题数据
  List<HotProjectsModel>? hotProjects;

  // 推荐分类导航
  List<CategoryBannersModel>? categoryBanners;

  // 首页滚动组件控制器
  late ScrollController _customScrollController;

  // TabController
  late TabController _controller;

  // 下拉刷新控制器
  late RefreshController _refreshController;

  // 回到顶部按钮的显示状态
  bool _showBackTop = false;

  // 发起网络请求的方法
  void _loadData() async {
    // 准备请求地址
    // String _url =
    //     'https://pcapi-xiaotuxian-front-devtest.itheima.net/home/index';

    // 创建httpClient
    // Dio dio = Dio();

    // 发送网络请求
    try {
      // 使用dio原本的get方法发送
      // Response res = await dio.get(_url);

      // 使用自定义类中的单例中的get方法
      // Response res = await PuppyRequestManager().dio!.get('/home/index');

      // 改用自定义的请求方法
      // Response res = await PuppyRequestManager().handleRequest(
      //   '/home/index',
      //   "GET",
      // );

      // 使用自定义接口HomeApi
      // Response res = await HomeApi.homeFetch();

      // 使用自定义接口HomeApi,并将返回的数据转化成模型数据
      HomeModel res = await HomeApi.homeFetch();
      setState(() {
        // 轮播图数据
        imageBanners = res.imageBanners;

        categoryGrids = res.categoryGrids;
        // 为了后续的演示效果,在加5个分类
        categoryGrids!.addAll(categoryGrids!.sublist(0, 7));
        categoryGrids!.addAll(categoryGrids!.sublist(0, 7));

        // 热门推荐数据
        hotRecommends = res.hotRecommends;

        // 新鲜好物
        freshGoods = res.freshGoods;

        // 热门品牌
        hotBrands = res.hotBrands;

        // 热门专题
        hotProjects = res.projects;

        // 推荐分类导航数据
        categoryBanners = res.categoryBanners;
        categoryBanners!.removeLast(); // 移除最后一项, 因为最后一项的商品个数不为10个 会报错

        // 拿到数据之后 创建TabController
        _controller = TabController(
          length: categoryBanners!.length,
          vsync: this,
        );
      });

      // 刷新完成
      _refreshController.refreshCompleted();

      // print(res);
      // 换debugPrint方法打印
      debugPrint('$res');
    } catch (e) {
      // print(e);
      // 刷新失败
      _refreshController.refreshFailed();
      debugPrint('$e');
    }
  }

  _loadMoreData() async {
    // 模拟加载更多数据
    await Future.delayed(Duration(seconds: 3));

    // 加载完成
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    // 测试单例
    // PuppyRequestManager p1 = PuppyRequestManager();
    // PuppyRequestManager p2 = PuppyRequestManager();

    // print(p1);
    // print(identical(p1, p2));

    // 测试单例dio
    // =======
    // PuppyRequestManager p1 = PuppyRequestManager();
    // PuppyRequestManager p2 = PuppyRequestManager();

    // print(p1.dio);
    // print(identical(p1.dio, p2.dio));

    // 这里创建TabController, 为了保证在拿到数据之前,可以使用一个正常的控制器
    _controller = TabController(length: 0, vsync: this);

    // 下拉刷新控制器
    _refreshController = RefreshController();

    // 首页滚动组件控制器
    _customScrollController = ScrollController();

    // 加载数据
    _loadData();
    super.initState();
  }

  // 销毁控制器
  @override
  void dispose() {
    // 释放TabController
    _controller.dispose();
    // 释放下拉刷新控制器
    _refreshController.dispose();
    // 释放首页滚动组件控制器
    _customScrollController.dispose();
    super.dispose();
  }

  double _categoryGoodsImgWidth = 0.0;
  double _tabBarView = 0.0;

  @override
  Widget build(BuildContext context) {
    // AutomaticKeepAliveClientMixin需要 调用父类的build方法, 保证页面状态不丢失
    super.build(context);

    // 计算分类商品图片的宽度
    double screenWidth = MediaQuery.of(context).size.width;
    _categoryGoodsImgWidth = (screenWidth - 10 * 5 - 5 * 2) * 0.5;

    // 计算TabBarView总高度, 一个分类商品盒子大高度 *  5
    _tabBarView = (_categoryGoodsImgWidth + 102) * 5;

    return Scaffold(
      backgroundColor: Color(0xfff7f7f7),
      appBar: HomeAppBar(),
      // 设置堆叠布局
      body: NotificationListener(
        // 监听滚动事件
        // ScrollNotification 保存滚动视图滚动状态的
        onNotification: (ScrollNotification scrollNotification) {
          // 监听首页滚动组件是否滚动
          // scrollNotification.depth == 0 表示当前滚动组件是首页的CustomScrollView
          // scrollNotification is ScrollEndNotification 表示滚动组件滚动结束
          if (scrollNotification.depth == 0 &&
              scrollNotification is ScrollEndNotification) {
            // 获取滚动的距离
            double scrollOffset = scrollNotification.metrics.pixels;

            // 屏幕高度
            double screenHeight = MediaQuery.of(context).size.height;

            if (scrollOffset >= screenHeight * 0.1) {
              // 显示 回到顶部按钮
              setState(() {
                _showBackTop = true;
              });
            } else {
              // 隐藏 回到顶部按钮
              setState(() {
                _showBackTop = false;
              });
            }
          }

          return true; // 不再继续冒泡, 不在继续下发通知
        },
        child: Stack(
          children: [
            CustomRefresher(
              controller: _refreshController,
              onRefresh: _loadData,
              onLoading: _loadMoreData,
              enablePullDown: true,
              enablePullUp: false,
              child: CustomScrollView(
                controller: _customScrollController,
                slivers: [
                  // 轮播图
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.only(
                        top: 10,
                        left: 5,
                        right: 5,
                        bottom: 5,
                      ),
                      child: ImageSwiperWidget(
                        height: 160,
                        imageBanners: imageBanners,
                        borderRadius: 5,
                        type: CustomSwiperPaginationType.dots,
                      ),
                    ),
                  ),
                  // 分类快捷入口
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.all(5),
                      child: CategoryGridsWidget(categoryGrids: categoryGrids),
                    ),
                  ),
                  // 热门推荐
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.all(5),
                      child: HotRecommendsWidget(hotRecommends: hotRecommends),
                    ),
                  ),
                  // 新鲜好物
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.all(5),
                      child: FreshGoodsWidget(freshGoods: freshGoods),
                    ),
                  ),
                  // 热门品牌
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.all(5),
                      child: HotBrandsWidget(hotBrands: hotBrands),
                    ),
                  ),
                  // 热门专题
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.all(5),
                      child: HotProjectsWidget(hotProjects: hotProjects),
                    ),
                  ),

                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.only(top: 5),
                      child: Container(),
                    ),
                  ),

                  // 吸顶的分类导航
                  // delegate构建吸顶视图
                  SliverPersistentHeader(
                    pinned: true, // 是否固定在顶部
                    // floating: true, // 是否可以浮动
                    delegate: CustomSliverPersistentHeaderDelegate(
                      tabBar: TabBar(
                        tabAlignment:
                            TabAlignment.center, // 标签居中,如果不设置,标签会默认与左侧有偏移空隙
                        controller: _controller, // 这里没有控制器字段的话,会报错
                        isScrollable: true, // 是否可以滚动
                        labelColor: Color(0xff27BA9B), // 选中的标签颜色
                        unselectedLabelColor: Color(0xFF333333),
                        indicator: BoxDecoration(), // 设置空样式
                        indicatorColor: Colors.green,
                        labelPadding: EdgeInsets.zero, // 指示器颜色
                        tabs: _buildTabBar(categoryBanners),
                      ),
                    ),
                  ),

                  // 推荐分类商品
                  SliverToBoxAdapter(
                    child: SizedBox(
                      height: _tabBarView,
                      // padding: EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
                      child: TabBarView(
                        controller: _controller,
                        children: _buildCategoryGoods(categoryBanners),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            _showBackTop
                ? Positioned(
                  right: 30,
                  bottom: 100,
                  child: ClipOval(
                    child: GestureDetector(
                      onTap: () {
                        // 滚动到顶部
                        _customScrollController.animateTo(
                          0,
                          duration: Duration(milliseconds: 500),
                          curve: Curves.ease,
                        );
                      },
                      child: Container(
                        width: 50,
                        height: 50,
                        decoration: BoxDecoration(color: Colors.black26),
                        child: Icon(Icons.arrow_upward),
                      ),
                    ),
                  ),
                )
                : Container(),
          ],
        ),
      ),
    );
  }

  // 构建推荐分类商品
  List<Widget> _buildCategoryGoods(
    List<CategoryBannersModel>? categoryBanners,
  ) {
    List<Widget> items = [];
    if (categoryBanners == null) {
      return items;
    }
    // for (var i = 0; i <= 7; i++) {
    for (var i = 0; i <= categoryBanners.length - 1; i++) {
      CategoryBannersModel categoryBanner = categoryBanners[i];
      items.add(
        StaggeredGridView.countBuilder(
          padding: EdgeInsets.all(5),
          crossAxisCount: 2,
          itemCount: 10,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          staggeredTileBuilder: (int index) {
            return StaggeredTile.fit(1);
          },
          itemBuilder: (BuildContext context, int index) {
            GoodsModel goods = categoryBanner.goods![index];
            return GestureDetector(
              onTap: () {
                debugPrint('点击了商品: ${goods.name}');
                // 跳转到商品详情页面
                Navigator.push(
                  context,
                  CupertinoPageRoute(
                    builder: (context) {
                      return GoodsDetailPage(id: goods.id!);
                    },
                  ),
                );
              },
              child: Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(color: Colors.white),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Image.network(
                    //   goods.picture!,
                    //   width: _categoryGoodsImgWidth,
                    //   fit: BoxFit.cover,
                    // ),
                    CustomImage(
                      url: goods.picture!,
                      width: _categoryGoodsImgWidth,
                      height: _categoryGoodsImgWidth,
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 8),
                      child: SizedBox(
                        height: 40,
                        child: Text(
                          goods.name!,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 13),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 8),
                      child: PriceWidget(price: goods.price!),
                    ),
                  ],
                ),
              ),
            );
          }, // 这里是每个格子的内容,
        ),
      );
    }
    return items;
  }

  // 构建分类导航的内容
  List<Widget> _buildTabBar(List<CategoryBannersModel>? categoryBanners) {
    List<Widget> items = [];

    if (categoryBanners == null) {
      return items;
    }

    // for (var i = 0; i <= categoryBanners.length - 1; i++) {
    for (var i = 0; i <= categoryBanners.length - 1; i++) {
      items.add(
        Container(
          height: 44,
          width: 60,
          alignment: Alignment.center,
          child: Row(
            children: [
              Container(
                width: 59,
                alignment: Alignment.center,
                child: Text(
                  categoryBanners[i].name!,
                  style: TextStyle(fontSize: 13),
                ),
              ),
              // 如果是最后一个元素, 不添加分割线
              i < (categoryBanners.length - 1)
                  ? Container(width: 1, height: 12, color: Colors.blueGrey)
                  : Container(),
            ],
          ),
        ),
      );
    }

    return items;
  }
}

// 自定义SliverPersistentHeaderDelegate子类,构建吸顶视图
class CustomSliverPersistentHeaderDelegate
    extends SliverPersistentHeaderDelegate {
  CustomSliverPersistentHeaderDelegate({this.tabBar});
  // 接收TabBar组件
  final TabBar? tabBar;

  // 构建吸顶视图内容
  @override
  Widget build(
    BuildContext context,
    double shrinkOffset, //记录吸顶之后底部视图的滚动距离(范围:0.0 ~ maxExtent)
    bool overlapsContent,
  ) {
    return Container(
      // 当视图未吸顶时, 展示灰色背景, 吸顶并且分类商品移动了30像素再变成白色
      decoration: BoxDecoration(
        color: shrinkOffset >= 30 ? Colors.white : Color(0xfff7f7f8),
      ),
      height: 44,
      child: tabBar,
    );
  }

  // 吸顶视图最大高度
  @override
  double get maxExtent => 44.0;

  // 吸顶视图最小高度
  @override
  double get minExtent => 44.0;

  // 在视图吸顶的时候, 是否需要重构吸顶视图 true:需要重构 false:不需要重构
  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
